package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.DoctorListAdapter;
import com.xn.app.muying.bean.DoctorListBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.view.MyListView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 医生列表页面
 * Created by Administrator on 2016/11/2.
 */
public class DoctorListActivity extends BaseActivity implements HttpUtil.OnGetDataListener, View.OnClickListener, AdapterView.OnItemClickListener,MyListView.IXListViewListener {

    private MyListView lv;
    private Handler handler = new Handler();
    private DoctorListAdapter doctorListAdapter;
    private TextView title;
    private ImageView back;
    private ArrayList<DoctorListBean> list = new ArrayList<>();
    //无网络页面
    private LinearLayout no_data_linearlayout = null;
    //显示数据
    private TextView no_data_textview = null;
    //加载框
    AlertDialog dialog;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //医生id
    private String doctorlist_id;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_list);
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.load_failed) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.load_failed) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();

        lv = (MyListView) findViewById(R.id.activity_doctor_list_listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        no_data_textview= (TextView) findViewById(R.id.no_data_textview);
        title = (TextView) findViewById(R.id.activity_doctor_list_title);
        back = (ImageView) findViewById(R.id.activity_doctor_list_back);
        back.setOnClickListener(this);
        doctorlist_id = getIntent().getStringExtra("doctorlist_id");
        //判断网络
        if (NetworkUtil.isNetworkAvailable(DoctorListActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(DoctorListActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            HttpUtil.getData(APIMethod.Home_DoctorList(doctorlist_id, currentPage, number), handler, this);
        } else {
            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
            no_data_textview.setText(R.string.no_network_hint);
        }
        doctorListAdapter = new DoctorListAdapter(DoctorListActivity.this, handler,imageLoader, options);
        lv.setAdapter(doctorListAdapter);
        lv.setOnItemClickListener(this);

    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            final String subDepartmentName = jsonObject.optString("subDepartmentName");
            //获取数据总量
            if (totalCount == 0) {
                totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
            }
            JSONArray items = jsonObject.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject jsonObject1 = items.getJSONObject(i);
                String name = jsonObject1.optString("name");
                String photoUrl = jsonObject1.optString("photoUrl");
                String professionalTitle = jsonObject1.optString("professionalTitle");
                String primaryDepartmentName = jsonObject1.optString("primaryDepartmentName");
                String primaryHospitalName = jsonObject1.optString("primaryHospitalName");
                String primaryHospitalLevel = jsonObject1.optString("primaryHospitalLevel");
                String specialty = jsonObject1.optString("specialty");
                String id = jsonObject1.optString("id");
                DoctorListBean doctorListBean = new DoctorListBean();
                doctorListBean.setName(name);
                doctorListBean.setPhotoUrl(photoUrl);
                doctorListBean.setProfessionalTitle(professionalTitle);
                doctorListBean.setPrimaryDepartmentName(primaryDepartmentName);
                doctorListBean.setPrimaryHospitalName(primaryHospitalName);
                doctorListBean.setPrimaryHospitalLevel(primaryHospitalLevel);
                doctorListBean.setSpecialty(specialty);
                doctorListBean.setId(id);
                list.add(doctorListBean);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    title.setText(subDepartmentName);
                }
            });
            if(list.size()>0){
                lv.setPullLoadEnable(true);
                lv.setXListViewListener(DoctorListActivity.this, totalCount, currentPage, number);
                onLoad();
                doctorListAdapter.getData(list);
                if(lv.getVisibility()==View.GONE){
                    lv.setVisibility(ListView.VISIBLE);
                }
                if(no_data_linearlayout.getVisibility()==View.VISIBLE){
                    no_data_linearlayout.setVisibility(LinearLayout.GONE);
                }

            }else{
                if(lv.getVisibility()==View.VISIBLE){
                    lv.setVisibility(ListView.GONE);
                }
                if(no_data_linearlayout.getVisibility()==View.GONE){
                    no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                }
                no_data_textview.setText("暂无该分类医生信息哦");
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_doctor_list_back:
                finish();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent();
        intent.putExtra("id", list.get(i).getId());
        intent.setClass(DoctorListActivity.this, DoctorInfoActivity.class);
        startActivity(intent);
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    //下滑加载
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        //下载数据
                        HttpUtil.getData(APIMethod.Home_DoctorList(doctorlist_id, currentPage, number), handler, DoctorListActivity.this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        lv.stopLoadMore();
    }
}
